import pyautogui
from openpyxl import load_workbook
import pandas as pd
import pyperclip
import time
import sys

# 图片路径
image_path1 = r'.\imgs\zdftjwxz.png'
image_path2 = r'.\imgs\zdftjxz.png'
code_path = r'.\imgs\code.png'
fiveMinute_path = r'.\imgs\5minute.png'
nextStep_path = r'.\imgs\nextStep.png'
percent_path = r'.\imgs\percent.png'
yuan_path = r'.\imgs\yuan.png'
gu_path = r'.\imgs\gu.png'
confirm_path = r'.\imgs\confirm.png'

# excel路径
excel_path = r'.\excels\right.xlsx'

# excel前多少行
excel_nrows = 50

def findPic(path):
    '''
    通过图片路径，返回图片坐标
    '''
    try:
        location = pyautogui.locateOnScreen(path)
        if(location):
            x, y = pyautogui.center(location)
            center = { 'x': x, 'y': y}
            left, top = location.left, location.top
            leftTop = {'x': left, 'y': top}
            picLoc = {
                'leftTop': leftTop,
                'center': center
            }
            print("找到图片", path)
            return picLoc
        else:
            print("未找到图片", path)
            return False
    except pyautogui.ImageNotFoundException:
        # 处理找不到图片的异常
        print("未找到图片", path)
        return False

def findMultiPic(paths):
    picLoc = False
    for path in paths:
        picLoc = findPic(path)
        if picLoc is not False:
            break
    return picLoc

def readExcel(path):
    # 读取 Excel 文件
    df = pd.read_excel(path, engine='openpyxl', nrows=excel_nrows)

    # 初始化最终的二维数组
    final_array = []

    # 获取唯一的 '计算后股数' 值
    unique_calculated_shares = df['计算后股数'].unique()

    # 遍历每个唯一的 '计算后股数'
    for shares in unique_calculated_shares:
        # 筛选出当前 '计算后股数' 的所有行
        filtered_df = df[df['计算后股数'] == shares]
        
        # 构建当前 '计算后股数' 的字典列表
        shares_array = []
        for index, row in filtered_df.iterrows():
            # 将行转换为字典，使用第一行作为键名
            row_dict = row.to_dict()
            shares_array.append(row_dict)
        
        # 将当前 '计算后股数' 的字典列表添加到最终的二维数组中
        final_array.append(shares_array)
    # 打印最终的二维数组
    # print(final_array)
    return final_array

def readExcelToOneArray(path):
    # 读取 Excel 文件
    df = pd.read_excel(path, engine='openpyxl', nrows=excel_nrows)

    # 初始化一维数组
    one_array = []

    # 遍历 DataFrame 的每一行
    for index, row in df.iterrows():
        # 将行转换为字典，使用第一行作为键名
        row_dict = row.to_dict()
        # 将字典添加到一维数组中
        one_array.append(row_dict)

    # 打印最终的一维数组
    # print(one_array)
    return one_array

# 找涨跌幅条件，并点击
def findZDF():
    picLoc1 = findMultiPic([image_path1, image_path2])
    if picLoc1:
        pyautogui.moveTo(picLoc1['center']['x'], picLoc1['center']['y'])
        # 点击鼠标左键
        pyautogui.click()
    else:
        sys.exit("程序被终止")

def findCode():
    # 找股票代码，并在输入框输入
    picLoc2 = findMultiPic([code_path])
    if picLoc2:
        pyautogui.moveTo(picLoc2['center']['x']+100, picLoc2['center']['y'])
        # 点击鼠标左键
        pyautogui.click()
    else:
        sys.exit("程序被终止")

def find5Minute():
    # 找股票代码，并在输入框输入
    picLoc = findPic(fiveMinute_path)
    if picLoc:
        pyautogui.moveTo(picLoc['center']['x'], picLoc['center']['y']+48)
        # 点击鼠标左键
        pyautogui.click()
    else:
        sys.exit("程序被终止")

def findNextStep():
    # 找股票代码，并在输入框输入
    picLoc = findPic(nextStep_path)
    if picLoc:
        pyautogui.moveTo(picLoc['center']['x'], picLoc['center']['y'])
        # 点击鼠标左键
        pyautogui.click()
        time.sleep(0.2)
    else:
        sys.exit("下一步程序被终止")

# 找到委托数量输入框，并输入
def inputEntrustNum(num, money, str):
    # 找委托比例的百分号，如果有，切换至委托数量
    percentPicLoc = findPic(percent_path)
    yuanPicLoc = findPic(yuan_path)
    guPicLoc1 = findPic(gu_path)

    # 数量偏移
    offsetX = 35
    input_offsetX = -75
    num_offsetY =  35
    yuan_offsetY = 64
    
    # 根据股票代码类型选择输入值
    input_value = money if str.startswith('688') else num
    
    # 处理百分比输入框
    if percentPicLoc is not False:
        pyautogui.moveTo(percentPicLoc['center']['x']+15, percentPicLoc['center']['y'])
        pyautogui.click()
        time.sleep(0.2)
        y_offset = yuan_offsetY if str.startswith('688') else num_offsetY
        pyautogui.moveTo(percentPicLoc['center']['x']+offsetX, percentPicLoc['center']['y']+y_offset)
        pyautogui.click()
        pyautogui.moveTo(percentPicLoc['center']['x']+input_offsetX, percentPicLoc['center']['y'])
        pyautogui.click()
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.typewrite(input_value, interval=0.05)
    
    # 处理元输入框
    if yuanPicLoc is not False:
        x_offset = input_offsetX if str.startswith('688') else 15
        pyautogui.moveTo(yuanPicLoc['center']['x']+x_offset, yuanPicLoc['center']['y'])
        pyautogui.click()
        if not str.startswith('688'):
            time.sleep(0.2)
            pyautogui.moveTo(yuanPicLoc['center']['x']+offsetX, yuanPicLoc['center']['y']+num_offsetY)
            pyautogui.click()
            pyautogui.moveTo(yuanPicLoc['center']['x']+input_offsetX, yuanPicLoc['center']['y'])
            pyautogui.click()
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.typewrite(input_value, interval=0.05)
    
    # 处理股数输入框
    if guPicLoc1 is not False:
        if str.startswith('688'):
            pyautogui.moveTo(guPicLoc1['center']['x']+15, guPicLoc1['center']['y'])
            pyautogui.click()
            time.sleep(0.2)
            pyautogui.moveTo(guPicLoc1['center']['x']+offsetX, guPicLoc1['center']['y']+yuan_offsetY)
            pyautogui.click()
            pyautogui.moveTo(guPicLoc1['center']['x']+input_offsetX, guPicLoc1['center']['y'])
            pyautogui.click()
        else:
            pyautogui.moveTo(guPicLoc1['center']['x']+input_offsetX, guPicLoc1['center']['y'])
            pyautogui.click()
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.typewrite(input_value, interval=0.05)


    

def findConfirm():
    # 找股票代码，并在输入框输入
    picLoc = findPic(confirm_path)
    if picLoc:
        pyautogui.moveTo(picLoc['center']['x'], picLoc['center']['y'])
        # 点击鼠标左键
        pyautogui.click()
    else:
        sys.exit("程序被终止")

def setList(str, group, waitTime=1.5):
    findZDF()
    time.sleep(0.5)
    # 鼠标移动至530,550
    pyautogui.moveTo(530, 550)
    # 点击鼠标左键
    pyautogui.click()
    time.sleep(0.2)
    pyperclip.copy(str)
    # 将代码粘贴进输入框
    pyautogui.hotkey('ctrl', 'v')
    # 等待输入框获取股票信息
    time.sleep(waitTime)
     # 鼠标移动至700,715
    pyautogui.moveTo(700, 715)
    pyautogui.click()
    # 模拟键盘输入 "3.5"
    pyautogui.typewrite('3.5', interval=0.05)
    # 进入下一步
    pyautogui.moveTo(860, 910)
    pyautogui.click()
    time.sleep(0.2)
    pyautogui.moveTo(620, 655)
    pyautogui.click()
    gushu = f"{group[0]['计算后股数']}"
    pyautogui.typewrite(gushu, interval=0.05)
    # 进入下一步
    pyautogui.moveTo(860, 910)
    pyautogui.click()
    time.sleep(0.2)
    pyautogui.click()
    time.sleep(0.2)
    # 设置日涨幅超3.5
    # find5Minute()
    # # 模拟键盘输入 "3.5"
    # pyautogui.typewrite('3.5', interval=0.05)
    # # 进入下一步
    # findNextStep()
    # gushu = f"{group[0]['计算后股数']}"
    # inputEntrustNum(gushu)
    # findNextStep()
    # findConfirm()
    # time.sleep(0.2)

guosheng_code_path = r'.\imgs\guosheng\code.png'
guosheng_zhangdiefu_path = r'.\imgs\guosheng\zhangdiefu.png'
guosheng_percent_path = r'.\imgs\guosheng\percent.png'
guosheng_price_path = r'.\imgs\guosheng\price.png'
guosheng_price5_path = r'.\imgs\guosheng\price5.png'
guosheng_guNumber_path = r'.\imgs\guosheng\number.png'
guosheng_lijixiadan_path = r'.\imgs\guosheng\lijixiadan.png'
guosheng_confirm_path = r'.\imgs\guosheng\confirm.png'
guosheng_confirm2_path = r'.\imgs\guosheng\confirm2.png'
guosheng_center_path = r'.\imgs\guosheng\center.png'
guosheng_shangchuan_path = r'.\imgs\guosheng\shangchuan.png'
def findGuoShengCode(str):
    x=740
    y=148
    pyautogui.moveTo(x, y)
    # 点击鼠标左键
    pyautogui.click()
    pyperclip.copy(str)
    pyautogui.hotkey('ctrl', 'a')
    # 将代码粘贴进输入框
    pyautogui.hotkey('ctrl', 'v')
    time.sleep(1.5)
    pyautogui.moveTo(x, y+58)
    pyautogui.click()

def findGuoShengPercent():
    # 找股票代码，并在输入框输入
    pyautogui.moveTo(895, 535)
    time.sleep(0.5)
    # 点击鼠标左键
    pyautogui.click()
    time.sleep(0.5)
    pyperclip.copy('3.5')
    pyautogui.hotkey('ctrl', 'a')
    # 将代码粘贴进输入框
    pyautogui.hotkey('ctrl', 'v')

# 找到委托价格并委托卖五价
def findGuoShengPrice():
    x=850
    y=775
    # 找买入价
    pyautogui.moveTo(x, y)
    # 点击鼠标左键
    pyautogui.click()
    pyautogui.moveTo(x, y+90)
    pyautogui.scroll(-150, x, y+90)
    time.sleep(.5)
    # 移动到卖5价，并点击
    pyautogui.moveTo(x, y+90+172)
    pyautogui.click()

# 找到委托价格并委托卖五价
def findGuNumber(number):
    # 找股票代码，并在输入框输入
    pyautogui.moveTo(700, 835)
    # 点击鼠标左键
    pyautogui.click()
    pyperclip.copy(str(number))
    pyautogui.hotkey('ctrl', 'a')
    # 将代码粘贴进输入框
    pyautogui.hotkey('ctrl', 'v')

# 找到立即下单并点击
def findLijixiadan():
    pyautogui.moveTo(915, 1310)
    # 点击鼠标左键
    pyautogui.click()

# 找到确定按钮并点击
def findGSConfirm():
    pyautogui.moveTo(800, 600)
    # 点击鼠标左键
    pyautogui.click()
# 找到第二步确定按钮并点击
def findGSConfirm2():
    pyautogui.moveTo(820, 730)
    # 点击鼠标左键
    pyautogui.click()


def setGuoShengList(str, group, waitTime=1.5):
    findGuoShengCode(str)
    findGuoShengPercent()
    findGuoShengPrice()
    findGuNumber(group[0]['计算后股数'])
    findLijixiadan()
    time.sleep(0.5)
    findGSConfirm()
    time.sleep(0.5)
    findGSConfirm2()
    time.sleep(0.2)
    # # 等待输入框获取股票信息
    # time.sleep(waitTime)
    # # 设置日涨幅超3.5
    # find5Minute()
    # # 模拟键盘输入 "3.5"
    # pyautogui.typewrite('3.5', interval=0.05)
    # # 进入下一步
    # findNextStep()
    # gushu = f"{group[0]['计算后股数']}"
    # inputEntrustNum(gushu)
    # findNextStep()
    # findConfirm()
    # time.sleep(0.2)

def findJKJ(jkj):
    pyautogui.moveTo(872, 665)
    # 点击鼠标左键
    pyautogui.click()
    pyautogui.hotkey('ctrl', 'a')
    pyautogui.typewrite(str(jkj))

def findHLPercent():
    pyautogui.moveTo(1135, 740)
    # 点击鼠标左键
    pyautogui.click()
    pyautogui.hotkey('ctrl', 'a')
    pyautogui.typewrite("-0.3")

# 找到委托价格并委托卖五价
def findGuoShengZYPrice():
    # 找股票代码，并在输入框输入
    pyautogui.moveTo(1050, 1050)
    # 点击鼠标左键
    pyautogui.click()
    time.sleep(0.2)
    # 移动到买5价，并点击
    pyautogui.moveTo(1020, 888)
    pyautogui.click()

def findCW():
    pyautogui.moveTo(820, 1190)
    # 点击鼠标左键
    pyautogui.click()
    time.sleep(0.2)
def setGuoShengZYList(str, group, waitTime=1.5):
    findGuoShengCode(str)
    time.sleep(0.2)
    findJKJ(group[0]['上涨8%'])
    findHLPercent()
    findGuoShengZYPrice()
    findCW()
    findLijixiadan()
    time.sleep(0.5)
    findGSConfirm()
    time.sleep(0.5)
    findGSConfirm2()
    time.sleep(1)

# 找股价条件，并点击
def findGJ():
    picLoc1 = findMultiPic([r'.\imgs\gjtj\gjtj1.png', r'.\imgs\gjtj\gjtj2.png'])
    if picLoc1:
        pyautogui.moveTo(picLoc1['center']['x'], picLoc1['center']['y'])
        # 点击鼠标左键
        pyautogui.click()
    else:
        sys.exit("程序被终止")

# 找股价达到，并点击
def findGJDD(up):
    picLoc1 = findMultiPic([r'.\imgs\gjtj\gjdd.png'])
    if picLoc1:
        pyautogui.moveTo(picLoc1['center']['x']+110, picLoc1['center']['y'])
        # 点击鼠标左键
        pyautogui.click()
        pyautogui.typewrite(up)
    else:
        sys.exit("程序被终止")

# 找委托价格，并点击
def findWTJG(entrust):
    picLoc1 = findMultiPic([r'.\imgs\gjtj\wtjg.png'])
    if picLoc1:
        pyautogui.moveTo(picLoc1['center']['x']+90, picLoc1['center']['y'])
        # 点击鼠标左键
        pyautogui.click()
        # 模拟ctrl+a,并输入entrust
        pyautogui.hotkey('ctrl', 'a')
        pyautogui.typewrite(entrust)
    else:
        sys.exit("程序被终止")
def setGJList(str, up, entrust, group, waitTime=0.5):
    findGJ()
    time.sleep(waitTime)
    findCode()
    pyperclip.copy(str)
    # 将代码粘贴进输入框
    pyautogui.hotkey('ctrl', 'v')
    # # 等待输入框获取股票信息
    time.sleep(waitTime)
    # 找到股价达到，并点击
    findGJDD(up)
    time.sleep(0.2)
    # 进入下一步
    findNextStep()
    findWTJG(entrust)
    gushu = f"{group[0]['计算后股数']}"
    inputEntrustNum(gushu)
    findNextStep()
    findConfirm()
    time.sleep(0.2)

def moveTo(x, y):
    # 获取当前屏幕尺寸
    screen_width, screen_height = pyautogui.size()
    print('当前屏幕尺寸', screen_width, screen_height)
    # 计算坐标比例
    x_ratio = x / 2560  # 假设原始屏幕宽度为2560
    y_ratio = y / 1440  # 假设原始屏幕高度为144
    # 根据当前屏幕尺寸计算实际坐标
    x = int(screen_width * x_ratio)
    y = int(screen_height * y_ratio)
    print(x, y)
    pyautogui.moveTo(x, y)
    

def setGJListByCoord(str, up, entrust, group, waitTime=0.5):
    # 点击股价条件
    moveTo(76, 200)
    pyautogui.click()
    time.sleep(waitTime)
    # 点击股票代码输入框
    moveTo(500, 545)
    pyautogui.click()
    time.sleep(waitTime)
    pyperclip.copy(str)
    # 将代码粘贴进输入框
    pyautogui.hotkey('ctrl', 'v')
    # # 等待输入框获取股票信息
    time.sleep(0.5)
    # 点击股价达到
    moveTo(660, 710)
    pyautogui.click()
    pyautogui.typewrite(up)
    time.sleep(waitTime)
    # 点击下一步
    moveTo(860, 912)
    pyautogui.click()
    time.sleep(waitTime)
    # 点击委托价格
    moveTo(620, 612)
    pyautogui.click()
    # 模拟ctrl+a,并输入entrust
    pyautogui.hotkey('ctrl', 'a')
    pyautogui.typewrite(entrust)
    time.sleep(waitTime)
    gushu = f"{group[0]['计算后股数']}"
    money = "6500"
    inputEntrustNum(gushu, money, str)
    time.sleep(waitTime)
    # 点击下一步
    moveTo(860, 912)
    pyautogui.click()
    time.sleep(waitTime)
    # 增加一个终止程序，如果找到确定按钮，就继续执行，否则终止程序
    confirmLoc = findPic(confirm_path)
    if confirmLoc:
        # 点击确定
        pyautogui.click()
    else:
        sys.exit("程序被终止")
    time.sleep(waitTime)
    

def setZFListByCoord(str, up, entrust, group, waitTime=0.5):
    # 点击股价条件
    moveTo(76, 265)
    pyautogui.click()
    time.sleep(waitTime)
    # # 点击股票代码输入框
    # moveTo(500, 545)
    # pyautogui.click()
    # time.sleep(waitTime)
    # pyperclip.copy(str)
    # # 将代码粘贴进输入框
    # pyautogui.hotkey('ctrl', 'v')
    # # # 等待输入框获取股票信息
    # time.sleep(0.5)
    # # 点击股价达到
    # moveTo(660, 710)
    # pyautogui.click()
    # pyautogui.typewrite(up)
    # time.sleep(waitTime)
    # # 点击下一步
    # moveTo(860, 912)
    # pyautogui.click()
    # time.sleep(waitTime)
    # # 点击委托价格
    # moveTo(620, 612)
    # pyautogui.click()
    # # 模拟ctrl+a,并输入entrust
    # pyautogui.hotkey('ctrl', 'a')
    # pyautogui.typewrite(entrust)
    # time.sleep(waitTime)
    # gushu = f"{group[0]['计算后股数']}"
    # money = "6500"
    # inputEntrustNum(gushu, money, str)
    # time.sleep(waitTime)
    # # 点击下一步
    # moveTo(860, 912)
    # pyautogui.click()
    # time.sleep(waitTime)
    # # 增加一个终止程序，如果找到确定按钮，就继续执行，否则终止程序
    # confirmLoc = findPic(confirm_path)
    # if confirmLoc:
    #     # 点击确定
    #     pyautogui.click()
    # else:
    #     sys.exit("程序被终止")
    # time.sleep(waitTime)